/** 
 * @Title:  UserAllInfoFragment.java 
 * @author:  Abtswiath丶lxy
 * @data:  2016年6月14日 上午10:45:06 <创建时间>
 * 
 * @history：<以下是历史记录>
 *
 * @modifier: <修改人>
 * @modify date: 2016年6月14日 上午10:45:06 <修改时间>
 * @log: <修改内容>
 *
 * @modifier: <修改人>
 * @modify date: 2016年6月14日 上午10:45:06 <修改时间>
 * @log: <修改内容>
 */
package com.sunmi.usercenter.ui.activity.fragment;

import java.lang.reflect.Type;
import java.util.List;

import org.apache.http.Header;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.sunmi.usercenter.Constant;
import com.sunmi.usercenter.R;
import com.sunmi.usercenter.bean.FmInfo;
import com.sunmi.usercenter.bean.Result;
import com.sunmi.usercenter.bean.Shop;
import com.sunmi.usercenter.bean.ShopType;
import com.sunmi.usercenter.bean.UserLoginInfo;
import com.sunmi.usercenter.bean.rpc.ReqGetUserInfo;
import com.sunmi.usercenter.bean.rpc.ReqUpdateShopAddress;
import com.sunmi.usercenter.bean.rpc.ReqUpdateShopName;
import com.sunmi.usercenter.bean.rpc.ReqUpdateShopType;
import com.sunmi.usercenter.bean.rpc.ReqUpdateShopUserName;
import com.sunmi.usercenter.controller.LocationController;
import com.sunmi.usercenter.ui.component.LoadingDialog;
import com.sunmi.usercenter.ui.component.UpdateDialog;
import com.sunmi.usercenter.ui.component.UpdateDialog.updateInfoLinstener;
import com.sunmi.usercenter.ui.component.UpdateTypeDialog;
import com.sunmi.usercenter.ui.component.UpdateTypeDialog.updateTypeLinstener;
import com.sunmi.usercenter.utils.CharUtils;
import com.sunmi.usercenter.utils.Validator;

import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * TODO<请描述这个类是干什么的>
 * 
 * @author Abtswiath丶lxy
 * @versionCode 1 <每次修改提交前+1>
 */
public class UserAllInfoFragment extends SuperFragment implements OnClickListener,BDLocationListener {

	private View mView;
	private RelativeLayout mRelNowAccount, mRelShopType, mRelShopName, mRelShopUserName, mRelShopAddress;
	private TextView mTxtPhone, mTxtShopType, mTxtShopName, mTxtShopUserName, mTxtShopAddress;
	private ImageView mImgLoading;
	private Shop shop;
	private UpdateDialog mUpdateDialog = null;
	private Animation operatingAnim;
	private RelativeLayout mRelBack;
	private LoadingDialog mLoadingDialog;
	private LocationController mLocationController;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		return mView = inflater.inflate(R.layout.fragment_user_center, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		verifyLogin();
		initView();
		fillData();
	}
	
	private void verifyLogin(){
		shop = mCaCheModel.getShop();
		if(shop==null){
			openFM(new FmInfo(LoginFragment.class, null));
			onDestroy();
		}
	}

	/**
	 * 填充数据
	 */
	private void fillData() {
		shop = mCaCheModel.getShop();
		if (shop != null) {
			String userName = shop.getUserName();
			if(Validator.isEmail(userName)){
				String string = "";
				for (int i = 0; i < (userName.split("@")[0].length()-3); i++) {
					string = string+"*";
				}
				mTxtPhone.setText(userName.substring(0,3) +string +"@" + userName.split("@")[1]);
			}else{
				mTxtPhone.setText(userName.substring(0,3) + "*****" + userName.substring(8, userName.length()));
			}
		}
		if (CharUtils.isEmpty(shop.getContactName())) {
			mTxtShopUserName.setText(getString(R.string.not_filled));
		}else{
			mTxtShopUserName.setText(shop.getContactName());
		}
		if (CharUtils.isEmpty(shop.getShopAddress())) {
			mTxtShopAddress.setText(getString(R.string.not_filled));
			mLocationController = LocationController.getInstance(getActivity(), this);
			mLocationController.start();
		}else{
			mTxtShopAddress.setText(shop.getShopAddress());
		}
		if (CharUtils.isEmpty(shop.getShopType())) {
			mTxtShopType.setText(getString(R.string.not_filled));
		}else{
			mTxtShopType.setText(shop.getShopType());
		}
		if (CharUtils.isEmpty(shop.getShopName())) {
			mTxtShopName.setText(getString(R.string.not_filled));
		}else{
			mTxtShopName.setText(shop.getShopName());
		}
	}
	
	

	/**
	 * 初始化
	 */
	private void initView() {
		mActivity.SetStatusColorFE542B();
		Constant.CLASS_FRAGMENT = Constant.DoubleClickExit;
		mRelBack = (RelativeLayout) mView.findViewById(R.id.back);
		mRelNowAccount = (RelativeLayout) mView.findViewById(R.id.rel_now_account);
		mRelShopType = (RelativeLayout) mView.findViewById(R.id.lin_shop_type);
		mRelShopName = (RelativeLayout) mView.findViewById(R.id.lin_shop_name);
		mRelShopUserName = (RelativeLayout) mView.findViewById(R.id.lin_shop_username);
		mRelShopAddress = (RelativeLayout) mView.findViewById(R.id.lin_shop_address);
		mTxtPhone = (TextView) mView.findViewById(R.id.txt_phone_hidi);
		mTxtShopType = (TextView) mView.findViewById(R.id.txt_shop_type);
		mTxtShopName = (TextView) mView.findViewById(R.id.txt_shop_name);
		mTxtShopUserName = (TextView) mView.findViewById(R.id.txt_shop_user_name);
		mTxtShopAddress = (TextView) mView.findViewById(R.id.txt_shop_address);
		mImgLoading = (ImageView) mView.findViewById(R.id.img_loading);
		operatingAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.check_anim);  
		LinearInterpolator lin = new LinearInterpolator();  
		operatingAnim.setInterpolator(lin);  
		mImgLoading.setVisibility(View.GONE);
		mRelNowAccount.setOnClickListener(this);
		mRelShopType.setOnClickListener(this);
		mRelShopName.setOnClickListener(this);
		mRelShopUserName.setOnClickListener(this);
		mRelShopAddress.setOnClickListener(this);
		mRelBack.setVisibility(View.GONE);
	}
	
	private LoadingDialog loadingDialog ;
	private void updateShopType(){
		loadingDialog = LoadingDialog.createDialog(getActivity(), getString(R.string.get_shop_type));
		loadingDialog.show();
		mHttpController.getAllShopType(new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				String json = new String(arg2);
				Gson gson = new Gson();
				Type type = new TypeToken<Result<List<ShopType>>>(){}.getType();
				Result<List<ShopType>> result = null;
				try {
					result = gson.fromJson(json,type);
				}catch (Exception e){
					e.printStackTrace();
				}
				if(result!=null&&result.code==1&&result.data!=null){
					List<ShopType> list = result.data;
					if(list!=null&&list.size()>0){
						loadingDialog.dismiss();
						updateShopTypeDialog(list);
					}
				}else{
					showToast(getString(R.string.get_error));
					loadingDialog.dismiss();
				}
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				showToast(getString(R.string.get_error));
				loadingDialog.dismiss();
			}
		});
	}
	
	private UpdateTypeDialog updateTypeDialog;
	private void updateShopTypeDialog(List<ShopType> list){
		updateTypeDialog = new UpdateTypeDialog(list,new updateTypeLinstener() {
			
			@Override
			public void click(String tid) {
				ReqUpdateShopType reqUpdateShopType = new ReqUpdateShopType();
				reqUpdateShopType.settId(tid);
				reqUpdateShopType.setuId(shop.getuId());
				mHttpController.updateShopType(reqUpdateShopType, asyncHttpResponseHandler);
			}
			
			@Override
			public void cancel() {
				updateTypeDialog.dismiss();
			}
		});
		updateTypeDialog.setStyle(DialogFragment.STYLE_NORMAL, R.style.defaultDialogStyle);
		updateTypeDialog.setCancelable(false);
//		updateTypeDialog.setCanceledOnTouchOutside(true);
		updateTypeDialog.show(getFragmentManager(), getTag());
	}
	
	private void updateShopUserName(){
		String defaultUserName=null;
		if(!CharUtils.isEmpty(shop.getContactName())){
			defaultUserName = shop.getContactName();
		}
		clearDialog();
		mUpdateDialog = UpdateDialog.createDialog(getActivity(), getString(R.string.please_input_shop_username), defaultUserName, 6, new updateInfoLinstener() {
			
			@Override
			public void save(String msg) {
				msg = msg.trim();
				if(msg.equals(shop.getContactName())){
					mUpdateDialog.dismiss();
					return;
				}
				if(!CharUtils.isEmpty(msg)){
					ReqUpdateShopUserName reqUpdateShopUserName = new ReqUpdateShopUserName();
					reqUpdateShopUserName.setContactName(msg);
					reqUpdateShopUserName.setuId(shop.getuId());
					mHttpController.updateShopUserName(reqUpdateShopUserName,asyncHttpResponseHandler);
				}else{
					showToast(getString(R.string.input_dont_null));
				}
			}
			@Override
			public void cancel() {
				mUpdateDialog.dismiss();
			}
		});
		mUpdateDialog.show();
	}
	
	private void updateShopAddress(){
		String defaultAddress=null;
		if(!CharUtils.isEmpty(shop.getShopAddress())){
			defaultAddress = shop.getShopAddress();
		}
		clearDialog();
		mUpdateDialog = UpdateDialog.createDialog(getActivity(), getString(R.string.please_input_shop_address), defaultAddress, 30, new updateInfoLinstener() {
			
			@Override
			public void save(String msg) {
				msg = msg.trim();
				if(msg.equals(shop.getShopAddress())){
					mUpdateDialog.dismiss();
					return;
				}
				if(!CharUtils.isEmpty(msg)){
					ReqUpdateShopAddress reqUpdateShopAddress = new ReqUpdateShopAddress();
					reqUpdateShopAddress.setShopAddress(msg);
					reqUpdateShopAddress.setuId(shop.getuId());
					mHttpController.updateShopAddress(reqUpdateShopAddress,asyncHttpResponseHandler);
					
				}else{
					showToast(getString(R.string.input_dont_null));
				}
			}
			@Override
			public void cancel() {
				mUpdateDialog.dismiss();
			}
		});
		mUpdateDialog.show();
	}
	
	private void analysis(byte[] arg2){
		if(mUpdateDialog!=null&&mUpdateDialog.isShowing()){
			mUpdateDialog.dismiss();
		}
		if(updateTypeDialog!=null){
			updateTypeDialog.dismiss();
		}
		String json = new String(arg2);
		Gson gson = new Gson();
		Result result = gson.fromJson(json, Result.class);
		if(result!=null&&result.code==1){
			showToast(getString(R.string.update_success));
//			mUpdateDialog.dismiss();
			againPullData();
		}else{
			showToast(getString(R.string.update_error));
//			mUpdateDialog.dismiss();
		}
	}
	
	private void updateShopName(){
		String defaultName=null;
		if(!CharUtils.isEmpty(shop.getShopName())){
			defaultName = shop.getShopName();
		}
		clearDialog();
		mUpdateDialog = UpdateDialog.createDialog(getActivity(), getString(R.string.please_input_shop_name), defaultName,15, new updateInfoLinstener() {
			
			@Override
			public void save(String msg) {
				msg = msg.trim();
				if(msg.equals(shop.getShopName())){
					mUpdateDialog.dismiss();
					return;
				}
				if(!CharUtils.isEmpty(msg)){
					ReqUpdateShopName updateShopName = new ReqUpdateShopName();
					updateShopName.setuId(shop.getuId());
					updateShopName.setShopName(msg);
					mHttpController.updateShopname(updateShopName,asyncHttpResponseHandler);
				}else{
					showToast(getString(R.string.input_dont_null));
				}
			}
			@Override
			public void cancel() {
				mUpdateDialog.dismiss();
			}
		});
		mUpdateDialog.show();
	}
	
	/**
	 * 重新拉取数据
	 */
	private void againPullData(){
		mImgLoading.setVisibility(View.VISIBLE);
		mImgLoading.startAnimation(operatingAnim);
		ReqGetUserInfo reqGetUserInfo = new ReqGetUserInfo();
		reqGetUserInfo.setuId(shop.getuId());
		mHttpController.getUserInfo(reqGetUserInfo, new AsyncHttpResponseHandler() {
			
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				String json = new String(arg2);
				Gson gson = new Gson();
				Type type = new TypeToken<Result<Shop>>(){}.getType();
				Result<Shop> result = null;
				try {
					result = gson.fromJson(json,type);
				}catch (Exception e){
					e.printStackTrace();
				}
				if(result!=null&&result.getCode()==1&&result.data!=null){
					mImgLoading.clearAnimation();
					mImgLoading.setVisibility(View.GONE);
					mCaCheModel.saveShop(result.data);
					fillData();
				}else{
					mImgLoading.clearAnimation();
					mImgLoading.setVisibility(View.GONE);
				}
			}
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				mImgLoading.clearAnimation();
				mImgLoading.setVisibility(View.GONE);
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.rel_now_account:
			openFM(new FmInfo(UserAcountFragment.class, null));
			break;
		case R.id.lin_shop_type:
			updateShopType();
			break;
		case R.id.lin_shop_name:
			updateShopName();
			break;
		case R.id.lin_shop_username:
			updateShopUserName();
			break;
		case R.id.lin_shop_address:
			updateShopAddress();
			break;
		default:
			break;
		}
	}
	
	private AsyncHttpResponseHandler asyncHttpResponseHandler = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			analysis(arg2);
		}
		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
			showToast(getString(R.string.update_error));
			mUpdateDialog.dismiss();
		}
	};
	
	private void clearDialog(){
		if(mUpdateDialog!=null){
			if(mUpdateDialog.isShowing()){
				mUpdateDialog.dismiss();
			}
			mUpdateDialog = null;
		}
	}

	@Override
	public void onReceiveLocation(BDLocation location) {
		String address = location.getAddrStr();
		if(!TextUtils.isEmpty(address)){
			ReqUpdateShopAddress reqUpdateShopAddress = new ReqUpdateShopAddress();
			reqUpdateShopAddress.setShopAddress(address);
			reqUpdateShopAddress.setuId(shop.getuId());
			mHttpController.updateShopAddress(reqUpdateShopAddress, asyncHttpResponseHandler);
			mLocationController.stop();
		}
	}
}
